<?php
/**
 * Products' categories model.
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 *
 */
class Models_ProductCategories extends Bel_Model_Tree {

	/**
	 * Array of tables' classes which are in one-to-many relation with products' categories table.  
	 *
	 * @var array
	 */	
	protected $_dependentTables = array ('Models_Products_Categories' );
	
	/**
	 * Initialization
	 *
	 * @param array $array
	 * @return void
	 */	
	public function __construct($array=array()){
		$this->table = TABLE_PREFIX.'product_categories';
		$this->table_id = 'category_id';
		$this->table_left = 'category_left_key';
		$this->table_right = 'category_right_key';
		$this->table_level = 'category_level';		
		$this->table_add_fields = array('category_name','category_description','category_keywords','category_image');
		parent::__construct ( $array );		
	}

	/**
	 * Return all children of specified category
	 *
	 * @param integer $node_id - id category to get children from
	 * @return array - array of stdObjects
	 */
	public function getChildren($node_id){
		return parent::getTreeBranch($node_id,$this->_primary[0].'<>'.$node_id);
	}

	/**
	 * Get all ancestors and siblings of specifiend category
	 *
	 * @param int $cat_id - category id to operate with
	 * @param int $max_level - max level of category to return
	 * @return array - array of stdObjects
	 */
	public function getAncestorsAndSiblings($cat_id, $max_level = null){		
		$parentBranch = $this->getParentBranch($cat_id,'category_level>1');

		$select = $this->select();
		
		foreach ($parentBranch as $node){
			$select->orWhere("category_level=($node->category_level+1) and category_left_key>$node->category_left_key and category_right_key<$node->category_right_key");
			$select->orWhere("category_level=($node->category_level) and category_left_key=$node->category_left_key and category_right_key=$node->category_right_key");	
		}
		
		if($max_level){
			$where = $select->getPart('where');
			$select->reset('where');
			$select->where('('.implode('',$where).')');		
			$select->where('category_level<='.$max_level);	
		}
		
		$select->order('category_left_key');
		
		return $this->_db->query($select)->fetchAll();
	}
	
}